﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Web;
using System.Diagnostics;

namespace Architecture.WCF.Tools
{
    public class ServiceMessageInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {

            if (request.Version != MessageVersion.None)
            {
                PipelineDiagnostic diagnostic = new PipelineDiagnostic()
                {
                    Operation = request.Headers.Action,
                    OperationDuration = -1
                };

                request.Headers.Add(diagnostic);
            }

            return Stopwatch.StartNew();
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            var watch = (Stopwatch)correlationState;
            watch.Stop();
            var duration = watch.ElapsedMilliseconds;
            
            Int32 index = OperationContext.Current.IncomingMessageHeaders.FindHeader(PipelineDiagnostic.HeaderName, PipelineDiagnostic.HeaderNamespace);
            if (index >= 0)
            {
                var diagnostic = OperationContext.Current.IncomingMessageHeaders.GetHeader<PipelineDiagnostic>(PipelineDiagnostic.HeaderName, PipelineDiagnostic.HeaderNamespace);
                diagnostic.OperationDuration = duration;
            }
            //Get original


        }
    }
}
